const RClass = require('./../utils/R.js');
const task = require('./../module/task');
const table = 'task';

const sqls = {
    checkCalcTarget(year,eday) {
        return `select * from (select count(*) as taskCount from task where task_content like "%${year}-${eday}%" and \`schedule\`> -1 and \`schedule\` < 100) a
, (select count(*) as resultCount from draught_result where path like "%${year}-${eday}.tif%") b`;
    },
    getCalaYearEday() {
        return `select a.year,a.eday from (select * from draught_source where dtype like "lst") a 
, (select * from draught_source where dtype like "ndvi") b
where a.year = b.year and a.eday = b.eday and a.year >= 2010`;
    }
};

let taskMethods = {
    db: null,
    table: null,
    defaultNotTran(R,err,ret) {
        if (err) {
            R.setError(err)
                .resCallBack();
        } else {
            R.resCallBack(ret);
        }
    },
    defaultCallBack(R,err,ret) {
        if (err) {
            R.setError(err)
                .resCallBack();
        } else {
            if (ret instanceof Array) {
                ret = ret.map(_ => new task().set(_));
            }
            R.resCallBack(ret);
        }
    },
    defaultAction(dbMethod,obj,cb){
        this.db[dbMethod]({
            table: this.table,
            ...obj
        },cb || this.defaultCallBack.bind(this,R));
    },
    // 这里直接为 getLimit(R)
    getLimit({ content: { param } }) {
        let page = parseInt(param.page);
        let size = parseInt(param.size);
        page = page.toString() === param.page ? page : false;
        size = size.toString() === param.size ? size : false;
        if (page && size) {
            return ` limit ${page * size},${size}`
        } else {
            return '';
        }
    },
    // 请求对象中 api 直接为 以下方法名称

    // 检查要计算的内容是否已经在计算或者已经有计算结果
    checkCalcTarget(db,R) {
        let { content : { param : { year, eday } } } = R;
        if (year && eday) {
            this.defaultAction.bind(this)('query',{
                sql: sqls.checkCalcTarget(year,eday)
            },this.defaultNotTran.bind(this,R));
        } else {
            this.defaultCallBack(R,"参数不正确");
        }
    },
    getCalaYearEday(db,R) {
        this.defaultAction.bind(this)('query',{
            sql: sqls.getCalaYearEday()
        },this.defaultNotTran.bind(this,R));
    },
};

/**
 * req、res 是请求时的两个对象
 * type 是请求类型 get 和 post
 * db 是数据库
 * */
module.exports = (db,requestType,req,res) => {
    let R = new RClass({
        req , res , requestType
    }).analizeReq();
    taskMethods.db = db;
    taskMethods.R = R;
    taskMethods.table = table;
    if (R.content.param.api in taskMethods) {
        taskMethods[R.content.param.api](db,R);
    } else {
        R.setError("接口不存在")
            .resCallBack();
    }
};